package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AwaitTerminationExampleService {

    private final ExecutorService executorService = Executors.newFixedThreadPool(5);

    public void executeTasksWithTermination() {
        // 提交一些任务
        executorService.submit(() -> {
            try {
                Thread.sleep(1000);
                log.info("任务 1 完成");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        executorService.submit(() -> {
            try {
                Thread.sleep(5000);
                log.info("任务 2 完成");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        // 关闭线程池，不再接受新任务
        executorService.shutdown();

        try {
            // 等待线程池中的所有任务完成，最多等待 3 秒钟
            if (executorService.awaitTermination(3, TimeUnit.SECONDS)) {
                log.info("所有任务完成");
            } else {
                log.info("超时，仍有任务未完成");
            }
        } catch (InterruptedException e) {
            log.error("等待过程中被中断", e);
            Thread.currentThread().interrupt();
        }
    }
}
